import account_distributedAccount from '@ohos.account.distributedAccount';
import { BusinessError } from '@ohos.base';
import Logger from './Logger';

const TAG = 'DistributedAccountHelper';

/**
 * 分布式账号类
 * 功能：
 * 1.判断是否登录
 * 2.登录默认账号
 */
export class DistributedAccountHelper {
  private distributedAccountAbility: account_distributedAccount.DistributedAccountAbility;

  constructor() {
    this.distributedAccountAbility = account_distributedAccount.getDistributedAccountAbility();
  }

  /**
   * 检查当前登录分布式账号信息
   * @returns Promise<boolean>
   */
  checkLogin(): Promise<void> {
    return new Promise((resolve, reject) => {
      this.distributedAccountAbility.getOsAccountDistributedInfo().then((data: account_distributedAccount.DistributedInfo) => {
        Logger.info(TAG, 'distributed information: ' + JSON.stringify(data));
        resolve();
      }).catch((err: BusinessError) => {
        Logger.info(TAG, 'getOsAccountDistributedInfo exception: ' + JSON.stringify(err));
        resolve();
      });
    });
  }

  /**
   * 登录分布式账号
   * @returns Promise<void>
   */
  login(): Promise<void> {
    let distributedInfo: account_distributedAccount.DistributedInfo = {
      name: 'ZhangSan',
      id: '12345',
      event: 'Ohos.account.event.LOGIN',
    };
    return new Promise((resolve, reject) => {
      this.distributedAccountAbility.setOsAccountDistributedInfo(distributedInfo).then(() => {
        Logger.info(TAG, 'setOsAccountDistributedInfo LOGIN successfully');
        resolve();
      }).catch((err: BusinessError) => {
        Logger.info(TAG, 'setOsAccountDistributedInfo exception: ' + JSON.stringify(err));
        reject(err);
      });
    });
  }
}